﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace CoreProcess.Utility
{
    public class XmlSerialize<T>
    {

        private string StorageBasePath = AppDomain.CurrentDomain.BaseDirectory + "\\";
  
        //d:\01/07/2014 14:17:05.xml
        public void ToXmlFile(T data,string filename)
        {
            
            var filePath =
                StorageBasePath;

            var idx =
                filePath.IndexOf("Personal_Resource_Management", System.StringComparison.Ordinal);

            filePath = filePath.Substring(0,idx);
            filePath += (@"Personal_Resource_Management\CoreProcess\XMLStorage\" + filename 
                                    //+ DateTime.Now.ToString("yyyyMMdd-HHmmss",CultureInfo.InvariantCulture) 
                                    + ".xml");

            using (var xmlWriter = new XmlTextWriter(filePath, Encoding.UTF8))
            {
                xmlWriter.Formatting = Formatting.Indented;//缩进？
                
                var xmlSerializer = new XmlSerializer(typeof(T));

                //if (_xmlSerializer == null) throw new ArgumentNullException("_xmlSerializer");

                xmlSerializer.Serialize(xmlWriter, data);
            }
        }

        public T FromXmlFile(String filePath)
        {
            using (var xmlReader = new XmlTextReader(filePath))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));

                return 
                    (T)xmlSerializer.Deserialize(xmlReader);
            }
        }
    }
}
